#import "LJClientPool.h"

@implementation LJClientPool
{
	id<ILJClientCreator> creator;
	NSMutableArray* states;
	NSMutableArray* clients;
}

-(id) initWithCreator:(id<ILJClientCreator>)creator
         AndSize:(int)size
{
    self = [super init];
    
	self->creator = creator;
    states = [NSMutableArray arrayWithCapacity:size];
    clients = [NSMutableArray arrayWithCapacity:size];
    
	for (int i = 0; i < size; i++)
	{
        [states addObject:[NSNumber numberWithBool:NO]];
        [clients addObject:[NSNull null]];
	}
    
    return self;
}

-(void)Doexecute:(ILJRequest*) request
        RspClass:(Class) rspClass
          andMsg:(NSString*)msg
         andView:(UIView*) vi
globalTimelinePostsWithBlock:(void (^)(id rsp))block
{
    int i = 0;
    do {
        for (i = 0; i < clients.count; i++)
        {
            // DONE: 线程安全处理
            @synchronized(self)
            {
                if (((NSNumber*)states[i]).boolValue == NO)
                {
                    states[i] = [NSNumber numberWithBool:YES];
                    break;
                }
            }
        }
    } while (i >= clients.count);
    
    if (clients[i] == [NSNull null]) {
        clients[i] = [creator newClient];
    }
    id<ILJClient> client = clients[i];
    [client Doexecute:request
             RspClass:rspClass
               andMsg:msg
              andView:vi
globalTimelinePostsWithBlock:^(id rsp){
      block(rsp);
      states[i] = [NSNumber numberWithBool:NO];
  }];
}

-(void)requestWithApiName:(NSString *)apiname
                   params:(NSMutableDictionary *)params 
                   andMsg:(NSString*)msg 
                   andView:(UIView*)vi 
                   globalTimelinePostsWithBlock:(void (^)(NSDictionary *posts, NSError *error))block
{
    int i = 0;
    do {
        for (i = 0; i < clients.count; i++)
        {
            // DONE: 线程安全处理
            @synchronized(self)
            {
                if (((NSNumber*)states[i]).boolValue == NO)
                {
                    states[i] = [NSNumber numberWithBool:YES];
                    break;
                }
            }
        }
    } while (i >= clients.count);
    
    if (clients[i] == [NSNull null]) {
        clients[i] = [creator newClient];
    }
    id<ILJClient> client = clients[i];
	[client requestWithApiName:apiname
                        params:params
                        andMsg:msg
                       andView:vi
  globalTimelinePostsWithBlock:^(NSDictionary *posts, NSError *error){
		block(posts, error);
        states[i] = [NSNumber numberWithBool:NO];
	}];
}
@end